#!/bin/bash

echo "MCSManager easy installation script for Linux"
echo "(c) 2021 CreeperKong"

# var init
DISTRO=NONE
NODE=16
NODEINST="no"
UN="no"
DIR="/opt/mcsm"
VERSION=$(curl --silent "https://gitee.com/api/v5/repos/Suwingser/MCSManager/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/' | sed -n 's/^.*v/v/p')

# Oracle
echo -e "\e[93mWARNING: If you are using Oracle Java SE, please read the license agreement carefully and make sure if you have a proper license. Both the authors of MCSManager and this script are NOT RESPONSIBLE for violation of Oracle's license agreement.\e[39m"

# Help
if [[ $@ = "-?" ]] || [[ $@ == "-h" ]]; then
  echo
  echo ""Usage: script [-s yes"|"no] [-n version] [-d DIR]""
  echo ""For "help", use [-h"|"-"?"]""
  echo
  echo ""[-s yes"|"no]"             " Silent installation, defalut option is no""
  echo ""[-d DIR]"                " Installation directory, default is /opt/mcsm""
  echo ""[-n "("Node.js Version")"]"  " Node.js version, defalut option is lts""
  echo """    "12"|"erbium"      "Node.js 12.x LTS""
  echo """    "14"|"fermium"     "Node.js 14.x LTS""
  echo """    "16"|"gallium"     "Node.js 16.x LTS""
  echo """    "current"        "Current version of Node.js""
  echo """    "lts"            "Latest LTS of Node.js""
  echo """    "no"             "Don"'"t install Node.js""
  echo
  exit 0
fi
# root?
if [[ "$(whoami)" != root ]]; then
  echo -e "\e[91mOnly user root can run this script.\e[39m"
  exit 1
fi

if [[ "$(uname -m)" != "x86_64" ]] || [[ "$(uname -m)" != "aarch64" ]]; then
  echo ""Installing "for" "$(uname -m)"...""
else
  echo -e "\e[91mCurrently, this script is not working for $(uname -m), the architectures supported are x86_64 and aarch64.\e[39m"
  echo -e "\e[93mIf you are running 32-bit OS on a 64-bit device, such as 64-bit Raspberry Pi or a x86_64 PC, get more information about how to install 64-bit OS from the manufacturer or the Internet.\e[39m" 
  exit 1
fi

while getopts n:d:s: opt
do
 case $opt in
  n) 
  NODE=$OPTARG
  echo -e "\e[92mYou have chosen to install Node.js $NODE.\e[39m"
  ;;
  d)
  DIR=$OPTARG
  ;;
  s)
  UN="$OPTARG"
 esac
done

# Silent?
if [ $UN == "yes" ] || [ $UN == "no" ]; then
  echo 
else
  echo -e "\e[91mSyntax error"!"\e[39m"
  echo ""[-s yes"|"no]"             " Silent installation, defalut option is no""
  exit 4
fi

# systemd?
if [ ! -d "/etc/systemd" ]; then
  echo -e "\e[91mThis script is only for systemd based distro. Check if you can upgrade to newer version of the distro with systemd.\e[39m"
  exit 2 
fi

# Get distro

if [ ! -f "/etc/debian_version" ]; then
  echo -e "\e[91mDebian (X)\e[39m"
else
  echo -e "\e[92mDebian (√)\e[39m"
  DISTRO=DEB
fi

if [ ! -f "/etc/redhat-release" ]; then
  echo -e "\e[91mRedhat (X)\e[39m"
else
  echo -e "\e[92mRedHat (√)\e[39m"
  DISTRO=RH
fi

if [ ! -f "/etc/arch-release" ]; then
  echo -e "\e[91mArch (X)\e[39m"
else
  echo -e "\e[92mArch (√)\e[39m"
  DISTRO=ARCH
fi

if [ $DISTRO == NONE ]; then
  echo -e "\e[91mCurrently not supported on this distro.\e[39m"
  exit 1
fi


# Node.js check
if [[ $NODE == no ]]; then
  echo -e "\e[93mYou have chosen not to install Node.js, make sure that you have it installed before.\e[39m"
fi

if [[ $NODE == current ]]; then
  echo -e "\e[93mYou have chosen to install current version of Node.js, which may be unstable, proceed with care.\e[39m"
fi

if [[ $NODE == 0 ]] || [[ $NODE == 1 ]] || [[ $NODE == 2 ]] || [[ $NODE == 3 ]] || [[ $NODE == 4 ]] || [[ $NODE == 5 ]] || [[ $NODE == 6 ]] || [[ $NODE == 7 ]] || [[ $NODE == 8 ]] || [[ $NODE == 9 ]] || [[ $NODE == 10 ]] || [[ $NODE == 11 ]] || [[ $NODE == dubnium ]] || [[ $NODE == carbon ]] || [[ $NODE == boron ]] || [[ $NODE == argon ]]; then
  echo -e "\e[91mThis version of Node.js is not supported by MCSManager.\e[39m"
  echo
  exit 5
fi

if [[ $NODE == 13 ]] || [[ $NODE == 15 ]]; then
  echo -e "\e[91mThis version of Node.js is no longer supported, for security reasons, installation cannot proceed.\e[39m"
  echo
  exit 5
fi

# Ask
echo "Installing to "$DIR""

if [[ $UN == "yes" ]]; then
  echo "Starting silent installation..."
else
    read -r -p "Proceed with installation? [Y/n] " input
    case $input in
        [yY][eE][sS]|[yY])
    		echo "Starting installation..."
    	;;
        [nN][oO]|[nN])
           exit 0
        ;;
        *)
	    	echo "\e[91mInvalid input...\e[39m"
	    	exit 3
		;;
esac
fi



# Install nodejs
if [ $NODE == no ]; then
  echo -e "\e[93mNot installing Node.js.\e[39m"
  NODEINST="yes"
fi
if [ $NODE == 12 ] || [ $NODE == erbium ]; then
    echo "Installing Node.js 12.x"
    if [ $DISTRO == DEB ]; then
            curl -fsSL https://deb.nodesource.com/setup_12.x | bash -
            apt-get install -y nodejs
            NODEINST="yes"
    fi
    if [ $DISTRO == RH ]; then
            curl -fsSL https://rpm.nodesource.com/setup_12.x | bash -
            yum install -y nodejs
            NODEINST="yes"
    fi
    if [ $DISTRO == ARCH ]; then
            pacman -Syu npm nodejs-lts-erbium --noconfirm
            NODEINST="yes"
    fi
fi
if [ $NODE == 16 ] || [ $NODE == gallium ] || [ $NODE == lts ]; then
    echo "Installing Node.js 16.x"
    if [ $DISTRO == DEB ]; then
        curl -fsSL https://deb.nodesource.com/setup_16.x | bash -
        apt-get install -y nodejs
        NODEINST="yes"
    fi
    if [ $DISTRO == RH ]; then
        curl -fsSL https://rpm.nodesource.com/setup_16.x | bash -
        yum install -y nodejs
        NODEINST="yes"
    fi
    if [ $DISTRO == ARCH ]; then
        pacman -Syu npm nodejs-lts-gallium --noconfirm
        NODEINST="yes"
    fi
fi
if [ $NODE == 14 ] || [ $NODE == fermium ]; then
    echo "Installing Node.js 14.x"
    if [ $DISTRO == DEB ]; then
        curl -fsSL https://deb.nodesource.com/setup_14.x | bash -
        apt-get install -y nodejs
        NODEINST="yes"
    fi
    if [ $DISTRO == RH ]; then
        curl -fsSL https://rpm.nodesource.com/setup_14.x | bash -
        yum install -y nodejs
        NODEINST="yes"
    fi
    if [ $DISTRO == ARCH ]; then
        pacman -Syu npm nodejs-lts-fermium --noconfirm
        NODEINST="yes"
    fi
fi
if [ $NODE == current ]; then
    echo "Installing Node.js current"
    if [ $DISTRO == DEB ]; then
        curl -fsSL https://deb.nodesource.com/setup_current.x | bash -
        apt-get install -y nodejs
        NODEINST="yes"
    fi
    if [ $DISTRO == RH ]; then
        curl -fsSL https://rpm.nodesource.com/setup_current.x | bash -
        yum install -y nodejs
        NODEINST="yes"
    fi
    if [ $DISTRO == ARCH ]; then
        pacman -Syu npm nodejs --noconfirm
        NODEINST="yes"
    fi
fi

# Node.js installation check
if [ $NODEINST == "no" ]; then
  echo -e "\e[91mNode.js installation failed, please try again or use -n no option to bypass Node.js installation.\e[39m"
  exit 5
fi

# Get MCSM
mkdir /tmp/mcsm
cd /tmp/mcsm
wget -O $VERSION.zip https://gitee.com/Suwingser/MCSManager/repository/archive/$VERSION?format=zip

# Put files into dir
unzip -o -qq $VERSION.zip
mkdir -p "$DIR"
mv -f MCSManager-$VERSION/* "$DIR"
mv -f MCSManager-$VERSION/.[!.]* "$DIR"

# Install modules
npm config set registry http://mirrors.cloud.tencent.com/npm/
cd "$DIR"
npm install
rm -rf /tmp/mcsm

# Add service
echo "[Unit]
Description=MCSManager

[Service]
ExecStart="$(which node)" "$DIR"/app.js
Restart=always
Environment=PATH=/usr/bin:/usr/local/bin:/usr/local/node/bin
Environment=NODE_ENV=production
WorkingDirectory="$DIR"

[Install]
WantedBy=multi-user.target 
" > /lib/systemd/system/mcsm.service


# Done
echo
echo -e "\e[44m\e[97m\e[5mInstallation completed!\e[0m"
echo
echo -e "\e[45m\e[97mUse the following command to get started":"\e[0m"
echo
echo -e """      ""\e[1mStart panel\e[0m""           ""\e[102m\e[30msystemctl start mcsm\e[0m"
echo -e """      ""\e[1mStop panel\e[0m""            ""\e[101m\e[97msystemctl stop mcsm\e[0m"
echo -e """      ""\e[1mRestart panel\e[0m""         ""\e[103m\e[30msystemctl restart mcsm\e[0m"
echo
echo -e "\e[45m\e[97mUse the following command to config auto-start":"\e[0m"
echo
echo -e """      ""\e[1mEnable auto-start\e[0m""     ""\e[106m\e[30msystemctl enable mcsm\e[0m"
echo -e """      ""\e[1mDisable auto-start\e[0m""    ""\e[105m\e[97msystemctl disable mcsm\e[0m"
echo
echo -e "\e[45m\e[97mFor feedback of MCSManager go to":"\e[0m"
echo
echo -e """      ""\e[1mGitHub\e[0m""                ""\e[4m\e[96mhttps://github.com/Suwings/MCSManager/issues\e[0m"
echo -e """      ""\e[1mQQ Group\e[0m""              ""\e[4m\e[96m287215485\e[0m"
echo